package com.ants.platform.core.cover;

import com.ants.platform.core.utils.StringEncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.ObjectUtils;

import java.util.Enumeration;
import java.util.Properties;

/**
 * 解析配置文件里面的加密配置
 *
 * @author liushun
 * @version 1.0
 * @Date 2016-03-04
 */
public class EncryptPropertyConfigurer extends PropertyPlaceholderConfigurer {

    private final Logger logger = LoggerFactory.getLogger(PropertyPlaceholderConfigurer.class);


    /**
     * 重写配置文件 解析加密密文
     *
     * @param propertyName  属性名称
     * @param propertyValue 值名称
     * @return
     */
    protected String convertProperty(String propertyName, String propertyValue) {
        logger.debug("key=" + propertyName + " , value=" + propertyValue);
        return super.convertProperty(propertyName, propertyValue);
    }


    /**
     * 重新加载Properties属性值
     * 当属性key中一个字符以@开头代表该属性是加密属性
     *
     * @param props
     */
    @Override
    protected void convertProperties(Properties props) {
        for (Enumeration propertyNames = props.propertyNames(); propertyNames.hasMoreElements(); ) {
            String propertyName = (String) propertyNames.nextElement();
            String propertyValue = props.getProperty(propertyName);
            if (propertyName.indexOf("@") == 0) {
                props.remove(propertyName);
                propertyName = propertyName.replace("@", "");
                propertyValue = StringEncryptUtil.decode(propertyValue);
                props.setProperty(propertyName, propertyValue);
            }
            String convertedValue = convertProperty(propertyName, propertyValue);
            if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue))
                props.setProperty(propertyName, convertedValue);
        }
        super.convertProperties(props);
    }


}
